# coding=utf-8
# !/usr/bin/python

'''
@usb Relay
@8 Key SRD-05VDC-SL-C 
@www.icstation.com
'''

import os
import time
import sys
import serial
import serial.tools.list_ports


class UsbRelay:  
    def __init__(self,):
        self.currentCode = bytearray(1)
        self.currentCode[0] = 0xFF
        self.usbrelay = None
        self.usbrelayport = ""
        self.init = False

    #def __del__(self):
    #    self.__usbrelay

    def setUsbRelayPort(self,port):
        self.usbrelayport = port

    def on(self, number):
        if number == 'K1':
            self.currentCode[0] &= 0b11111110
            print "on K1"
        elif number == 'K2':
            self.currentCode[0] &= 0b11111101
            print "on K2"
        elif number == 'K3':
            self.currentCode[0] &= 0b11111011
            print "on K3"
        elif number == 'K4':
            self.currentCode[0] &= 0b11110111
            print "on K4"
        elif number == 'K5':
            self.currentCode[0] &= 0b11101111
            print "on K5"
        elif number == 'K6':
            self.currentCode[0] &= 0b11011111
            print "on K6"
        elif number == 'K7':
            self.currentCode[0] &= 0b10111111
            print "on K7"
        elif number == 'K8':
            self.currentCode[0] &= 0b01111111
            print "on K8"
        else:
            raise Exception("invalid argument!")
        if self.usbrelay != None:
            self.usbrelay.write(self.currentCode)

    def off(self, number):
        if number == 'K1':
            self.currentCode[0] |= 0b00000001
            print "off K1"
        elif number == 'K2':
            self.currentCode[0] |= 0b00000010
            print "off K2"
        elif number == 'K3':
            self.currentCode[0] |= 0b00000100
            print "off K3"
        elif number == 'K4':
            self.currentCode[0] |= 0b00001000
            print "off K4"
        elif number == 'K5':
            self.currentCode[0] |= 0b00010000
            print "off K5"
        elif number == 'K6':
            self.currentCode[0] |= 0b00100000
            print "off K6"
        elif number == 'K7':
            self.currentCode[0] |= 0b01000000
            print "off K7"
        elif number == 'K8':
            self.currentCode[0] |= 0b10000000
            print "off K8"
        else:
            raise Exception("invalid argument!")

        if self.usbrelay != None:
            self.usbrelay.write(self.currentCode)
    '''
    def reset(self):
        self.__currentCode[0] = 0xFF
        self.__usbrelay.write(self.__currentCode)
    '''
    def allon(self):
        self.currentCode[0] = 0x0
        if self.usbrelay != None:
            self.usbrelay.write(self.currentCode)

    def alloff(self):
        print "turn off all circuit"
        self.currentCode[0] = 0xFF
        if self.usbrelay != None:
            self.usbrelay.write(self.currentCode)

    def getCurrentCode(self):
        return self.currentCode

    def setCurrentCode(self,currentCode):
        self.currentCode = currentCode

    def initUsbRelay(self):
        print "initUsbRelay"
        if self.init is False: # init one time
            start_code = bytearray(1)
            activation_code = bytearray(1)
            start_code[0] = 80
            activation_code[0] = 81
            self.usbrelay = serial.Serial(self.usbrelayport, 9600)
            self.usbrelay.write(start_code)
            #if 0xAC != self.usbrelay.read(1):
               #raise Exception("the usb relay is not 8 ...")
            time.sleep(2)
            self.usbrelay.write(activation_code)
            self.init = True

    def isPortOpen(self):
        if self.usbrelay is None or self.usbrelay.port is None:
            return False
        else:
            return self.usbrelay.isOpen()

    def closePort(self):
        if self.isPortOpen() is True:
            self.usbrelay.close()
            print 'Close usb relay port %s successfully.' % self.usbrelay.port
        else:
            print 'Close usb relay port %s failed.' % self.usbrelay.port



if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding('utf-8')
    usbrelay = UsbRelay()
    usbrelay.setUsbRelayPort("COM5")
    #print usbrelay.isPortOpen()
    usbrelay.initUsbRelay()
    usbrelay.isPortOpen()
    
    #test2
    #K3 1000 times
    '''
    n=0
    while n<1000:
        usbrelay.on('K3')
        time.sleep(0.1)
        usbrelay.off('K3')
        time.sleep(0.1)
        n+=1
        print "time " + str(n)
    '''


    #test1
    
    #usbrelay.on('K2')
    #time.sleep(0.1)
    #usbrelay.off('K2')
    #usbrelay.on('K6')
    #time.sleep(1)
    #usbrelay.off('K6')
    usbrelay.allon()
    time.sleep(1)
    usbrelay.alloff()
    usbrelay.closePort()
    #all test
    '''
    usbrelay.on('K1')
    usbrelay.on('K2')
    usbrelay.on('K3')
    usbrelay.on('K4')
    usbrelay.on('K5')
    usbrelay.on('K6')
    usbrelay.on('K7')
    usbrelay.on('K8')
    #usbrelay.reset()
    usbrelay.alloff()
    usbrelay.allon()
    usbrelay.off('K1')
    usbrelay.off('K2')
    usbrelay.off('K3')
    usbrelay.off('K4')
    usbrelay.off('K5')
    usbrelay.off('K6')
    usbrelay.off('K7')
    usbrelay.off('K8')
    '''